/******************************************************************************
 * Copyright 2022 The Airos Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#pragma once
#include <list>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>

namespace air {
namespace link {

class App;
class Msg;
class EventConn;
class EventConnManager final {
  friend class App;

 public:
  EventConnManager();
  virtual ~EventConnManager();

  bool Init(std::shared_ptr<App> app, int sz = 2);

  std::shared_ptr<EventConn> Get();

  std::shared_ptr<EventConn> Get(int handle);

  void Release(std::shared_ptr<EventConn>);

 private:
  void AddEventConn();
  void Notify(const std::string& name, std::shared_ptr<Msg> msg);

  int conn_sz_ { 0 };
  std::mutex mtx_;
  std::unordered_map<int, std::string> run_conn_map_;
  std::unordered_map<std::string, std::shared_ptr<EventConn>> run_conn_;
  std::list<std::shared_ptr<EventConn>> idle_conn_;

  std::weak_ptr<App> app_;
};

}  // namespace link
}  // namespace air
